const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const success = require('../../utils/responses').success;
const failure = require('../../utils/responses').failure;
const NotFoundError = require('../../utils/errors').NotFoundError;

const moment = require('moment');
moment.locale('zh-cn'); // 如果需要设置中文本地化等相关配置可以加上这行

// 连接 MongoDB 数据库，替换为你自己的真实连接字符串
mongoose.connect('mongodb://localhost:27017/control-book', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const Book = require('../../models/book');
const Borrow = require('../../models/borrow');
const User = require('../../models/user');

//必须通过查询整张表，然后关联books,users，最后在全部查询的时候就可以同时显示出书籍的信息和借阅人的信息
//对应前端还书页面
router.get('/all', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage) || 1);
    const pageSize = Math.abs(Number(query.pageSize) || 10);
    const skip = (currentPage - 1) * pageSize;
    const condition = {};

    // 处理查询条件
    if (req.query.bookId) {
      condition.bookId = req.query.bookId;
    }

    // 处理分页
    const count = await Borrow.countDocuments(condition);

    const borrow = await Borrow.find(condition)
    .populate('bookId')
    .populate('userId')
    .skip(skip)
    .limit(pageSize)
    .exec();
    success(res, '查询所有借阅记录成功。', {
      borrow,
      pagination: {
        total: count,
        currentPage,
        pageSize
      }
    });
  } catch (error) {
    console.log(error);
    failure(res, error);
  }
})


// 点赞、取消赞
router.post('/', async function (req, res) {
  try {
      const userId = req.user.id;
      const { bookId } = req.body;
      console.log(bookId)
      console.log(req.user.username)
      const username = req.user.username;

      const book = await Book.findById(bookId);
      if (!book) {
          throw new NotFoundError('书籍不存在');
      }

      const borrow = await Borrow.findOne({ bookId, userId });
      console.log(borrow);

      // 如果没有点赞过，那就新增。
      if (!borrow) {
          const newBorrow = new Borrow({ bookId, userId,
            createdAt: moment().format('YYYY-MM-DD HH:mm:ss'), 
            updatedAt: moment().format('YYYY-MM-DD HH:mm:ss') });
          await newBorrow.save();
          await book.save();
          success(res, '借阅成功。');
      } else {
          // 如果借阅过了，那就删除。并且书籍的 likesCount - 1
          await borrow.deleteOne();
          await book.save();
          success(res, '取消借阅成功。');
      }

  } catch (error) {
    console.log(error);
      failure(res, error);
  }
});

// 查询用户借阅的书籍  人查书
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    // 查询当前用户（这里只是简单校验下用户是否存在，可根据实际情况完善错误处理逻辑）
    console.log(query.userId)
    const user = await User.findById(query.userId);
    console.log('~~~~~~~~~~~~~~~~~~~~~')
    if (!user) {
      throw new NotFoundError('用户不存在');
    }

    // 先在Borrow表中根据userId查找对应的bookId列表
    const BorrowBookId = await Borrow.find({
      userId: query.userId
    })
   .select('bookId')
   .exec();

    const bookIds = BorrowBookId.map(borrow => borrow.bookId);

    // 再根据获取到的bookId列表在Book表中查询对应的书籍
    const books = await Book.find({
      _id: {
        $in: bookIds
      }
    })
   .select('-CategoryId -UserId') // 排除指定字段
   .sort({ id: -1 })
   .limit(pageSize)
   .skip(offset);

   //返回是书籍信息可以写在我的里面，这就达成了分离的效果
   //那么借阅按钮，就用的是这里的接口
   //还书按钮，在这个接口里面，就可以删除了，那么就不再需要在book表中绑定userId了
   //这也就实现了第三范式

   //那么借书还书的选项，似乎就可以在borrow中搜索出bookId，并在前端加入数组，然后遍历数组，显示出对应的按钮。

    // 查询当前用户点赞过的书籍总数
    const count = await Book.countDocuments({
      _id: {
        $in: bookIds
      }
    });

    success(res, '查询用户点赞的书籍成功。', {
      books,
      username: user.username,
      pagination: {
        total: count,
        currentPage,
        pageSize
      }
    });
  } catch (error) {
    failure(res, error);
  }
});

// 查询书籍被借阅的用户  书查人
router.get('/:_id', async function (req, res) {
  try {
    const book = await Book.findById(req.params._id);
    const currentPage = Math.abs(Number(req.query.currentPage)) || 1;
    const pageSize = Math.abs(Number(req.query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    if (!book) {
      throw new NotFoundError('书籍不存在');
    }

    // 先在Borrow表中根据bookId查找对应的userId列表
    const BorrowBookId = await Borrow.find({
      bookId: req.params._id
    })
    .populate('userId')
   .select('userId')
   .exec();
   console.log(BorrowBookId);

    const userIds = BorrowBookId.map(borrow => borrow.userId);
    console.log(userIds);

    // 再根据获取到的bookId列表在Book表中查询对应的书籍
    const books = await User.find({
      _id: {
        $in: userIds
      }
    })
   .select('-CategoryId -UserId') // 排除指定字段
   .sort({ id: -1 })
   .limit(pageSize)
   .skip(offset);

    // 查询当前用户点赞过的书籍总数
    const count = await User.countDocuments({
      _id: {
        $in: userIds
      }
    });

    success(res, '查询用户点赞的书籍成功。', {
      books,
      pagination: {
        total: count,
        currentPage,
        pageSize
      }
    });
  } catch (error) {
    console.log(error);
    failure(res, error);
  }
});

//管理员还书 (强制删除)
router.delete('/:_id', async function (req, res) {
  try {
    const bookId = req.params._id; // 将从URL获取的值当作bookId来使用
    console.log(bookId);
    const borrow = await Borrow.findOne({ bookId: bookId }).exec();
    console.log(borrow)
    if (!borrow) {
      throw new NotFoundError('借阅记录不存在');
    }
    await borrow.deleteOne();
    success(res, '还书成功。');
  } catch (error) {
    console.log(error);
    failure(res, error);
  }
})

module.exports = router;